package com.whoiszxl.admin.controller.common;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import com.wf.captcha.base.Captcha;
import com.whoiszxl.admin.cqrs.response.CaptchaResponse;
import com.whoiszxl.common.constants.RedisPrefixConstants;
import com.whoiszxl.common.properties.CaptchaProperties;
import com.whoiszxl.starter.captcha.graphic.core.GraphicCaptchaService;
import com.whoiszxl.starter.redisson.RedisUtils;
import com.whoiszxl.starter.web.model.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDateTime;

@SaIgnore
@Tag(name = "验证码 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/captcha")
public class CaptchaController {

    private final GraphicCaptchaService graphicCaptchaService;

    private final CaptchaProperties captchaProperties;

    @GetMapping("/image")
    @Operation(summary = "获取图片验证码", description = "获取一个Base64格式的验证码")
    public R<Object> getImageCaptcha() {
        //1. 生成图片验证码
        Captcha captcha = graphicCaptchaService.getCaptcha();

        //2. 将验证码和 uuid 及过期时间存入 Redis，并返回前端
        String uuid = IdUtil.fastSimpleUUID();
        String captchaKey = RedisPrefixConstants.Admin.ADMIN_CAPTCHA_IMAGE_KEY + uuid;
        long expireTime = LocalDateTimeUtil.toEpochMilli(
                LocalDateTime.now().plusMinutes(captchaProperties.getExpirationInMinutes()));
        RedisUtils.set(captchaKey, captcha.text(), Duration.ofMinutes(captchaProperties.getExpirationInMinutes()));
        return R.ok(CaptchaResponse.builder().uuid(uuid).img(captcha.toBase64()).expireTime(expireTime).build());
    }

}
